<?php
session_start();
require_once '../classes/Database.php';
require_once '../classes/SettingsHelper.php';

        // 检查登录状态
        if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
            header('Location: login.php');
            exit;
        }

        $db = Database::getInstance();
        
        // 处理密码修改
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'change_password') {
            $currentPassword = $_POST['current_password'] ?? '';
            $newPassword = $_POST['new_password'] ?? '';
            $confirmPassword = $_POST['confirm_password'] ?? '';
            
            // 验证当前密码
            $adminUsername = $_SESSION['admin_username'];
            $result = $db->query("SELECT password FROM admin_users WHERE username = ?", [$adminUsername]);
            
            if (empty($result)) {
                $message = '管理员账户不存在';
                $messageType = 'danger';
            } elseif (!password_verify($currentPassword, $result[0]['password'])) {
                $message = '当前密码错误';
                $messageType = 'danger';
            } elseif ($newPassword !== $confirmPassword) {
                $message = '新密码和确认密码不一致';
                $messageType = 'danger';
            } elseif (strlen($newPassword) < 6) {
                $message = '新密码长度至少6位';
                $messageType = 'danger';
            } else {
                // 更新密码
                $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                $success = $db->query("UPDATE admin_users SET password = ? WHERE username = ?", [$hashedPassword, $adminUsername]);
                
                if ($success) {
                    $message = '密码修改成功';
                    $messageType = 'success';
                } else {
                    $message = '密码修改失败';
                    $messageType = 'danger';
                }
            }
        }

// 创建SettingsHelper实例
$settingsHelper = SettingsHelper::getInstance();

// 处理表单提交
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_system') {
        // 更新系统设置
        $settings = [
            'site_name' => $_POST['site_name'] ?? '',
            'site_url' => $_POST['site_url'] ?? '',
            'admin_email' => $_POST['admin_email'] ?? '',
            'currency' => $_POST['currency'] ?? '',
            'timezone' => $_POST['timezone'] ?? ''
        ];
        
        foreach ($settings as $key => $value) {
            $settingsHelper->saveSetting($key, $value, 'string', '系统设置');
        }
        
        $message = '系统设置已更新';
        $messageType = 'success';
        
    } elseif ($action === 'update_payment') {
        // 更新支付设置
        $settings = [
            'easypay_pid' => $_POST['easypay_pid'] ?? '',
            'easypay_key' => $_POST['easypay_key'] ?? '',
            'easypay_api_url' => $_POST['easypay_api_url'] ?? '',
            'easypay_notify_url' => $_POST['notify_url'] ?? '',
            'easypay_return_url' => $_POST['return_url'] ?? ''
        ];
        
        foreach ($settings as $key => $value) {
            $settingsHelper->saveSetting($key, $value, 'string', '易支付配置');
        }
        
        $message = '支付设置已更新';
        $messageType = 'success';
        
    } elseif ($action === 'update_security') {
        // 更新安全设置
        $settings = [
            'max_login_attempts' => $_POST['max_login_attempts'] ?? '',
            'session_timeout' => $_POST['session_timeout'] ?? '',
            'enable_captcha' => isset($_POST['enable_captcha']) ? '1' : '0',
            'enable_2fa' => isset($_POST['enable_2fa']) ? '1' : '0'
        ];
        
        foreach ($settings as $key => $value) {
            $settingsHelper->saveSetting($key, $value, 'string', '安全设置');
        }
        
        $message = '安全设置已更新';
        $messageType = 'success';
        
    } elseif ($action === 'update_email') {
        // 更新邮件设置
        $settings = [
            'smtp_host' => $_POST['smtp_host'] ?? '',
            'smtp_port' => $_POST['smtp_port'] ?? '',
            'smtp_user' => $_POST['smtp_user'] ?? '',
            'smtp_pass' => $_POST['smtp_pass'] ?? '',
            'from_email' => $_POST['from_email'] ?? '',
            'from_name' => $_POST['from_name'] ?? '',
            'enable_smtp' => isset($_POST['enable_smtp']) ? '1' : '0'
        ];
        
        foreach ($settings as $key => $value) {
            $settingsHelper->saveSetting($key, $value, 'string', '邮件设置');
        }
        
        $message = '邮件设置已更新';
        $messageType = 'success';
    }
}

// 获取当前设置用于表单显示
$currentSettings = [
    'site_name' => getSystemSetting('site_name', 'CDK支付系统'),
    'site_url' => getSystemSetting('site_url', 'http://localhost/cdkpay'),
    'admin_email' => getSystemSetting('admin_email', 'admin@example.com'),
    'currency' => getSystemSetting('currency', 'CNY'),
    'timezone' => getSystemSetting('timezone', 'Asia/Shanghai'),
    
    'easypay_pid' => getSystemSetting('easypay_pid', '1000'),
    'easypay_key' => getSystemSetting('easypay_key', 'your_key_here'),
    'easypay_api_url' => getSystemSetting('easypay_api_url', 'https://zf.tuour.com/submit.php'),
    'easypay_notify_url' => getSystemSetting('easypay_notify_url', 'http://localhost/cdkpay/notify.php'),
    'easypay_return_url' => getSystemSetting('easypay_return_url', 'http://localhost/cdkpay/return.php'),
    
    'max_login_attempts' => getSystemSetting('max_login_attempts', '5'),
    'session_timeout' => getSystemSetting('session_timeout', '30'),
    'enable_captcha' => getSystemSetting('enable_captcha', '1'),
    'enable_2fa' => getSystemSetting('enable_2fa', '0'),
    
    'smtp_host' => getSystemSetting('smtp_host', 'smtp.example.com'),
    'smtp_port' => getSystemSetting('smtp_port', '587'),
    'smtp_user' => getSystemSetting('smtp_user', 'your_email@example.com'),
    'smtp_pass' => getSystemSetting('smtp_pass', ''),
    'from_email' => getSystemSetting('from_email', 'noreply@example.com'),
    'from_name' => getSystemSetting('from_name', 'CDK支付系统'),
    'enable_smtp' => getSystemSetting('enable_smtp', '0')
];

// 获取系统信息
$mysqlVersion = '未知';
try {
    $result = $db->query("SELECT VERSION() as version");
    $mysqlVersion = !empty($result) ? $result[0]['version'] : '未知';
} catch (Exception $e) {
    $mysqlVersion = '未知';
}

$systemInfo = [
    'php_version' => PHP_VERSION,
    'mysql_version' => $mysqlVersion,
    'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? '未知',
    'upload_max_filesize' => ini_get('upload_max_filesize'),
    'max_execution_time' => ini_get('max_execution_time'),
    'memory_limit' => ini_get('memory_limit'),
];
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统设置 - <?php echo htmlspecialchars(getSiteName()); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="assets/admin.css" rel="stylesheet">
    <style>
        .settings-section {
            margin-bottom: 30px;
        }
        .info-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .form-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏（移动端显示） -->
    <div class="top-navbar d-flex align-items-center justify-content-between">
        <button class="sidebar-toggle">
            <i class="fas fa-bars"></i>
        </button>
        <h5 class="mb-0">系统设置 - <?php echo htmlspecialchars(getSiteName()); ?></h5>
        <div class="text-muted small">
            <i class="fas fa-user me-1"></i><?php echo htmlspecialchars($_SESSION['admin_username']); ?>
        </div>
    </div>

    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h4 class="mb-3">
                <i class="fas fa-cogs me-2"></i><span><?php echo htmlspecialchars(getSiteName()); ?></span>
            </h4>
            <p class="text-muted mb-0 small">欢迎, <?php echo htmlspecialchars($_SESSION['admin_username']); ?></p>
        </div>
        
        <nav class="nav flex-column">
            <a href="index.php" class="nav-link" data-tooltip="仪表盘">
                <i class="fas fa-tachometer-alt"></i><span>仪表盘</span>
            </a>
            <a href="products.php" class="nav-link" data-tooltip="商品管理">
                <i class="fas fa-box"></i><span>商品管理</span>
            </a>
            <a href="cdks.php" class="nav-link" data-tooltip="CDK管理">
                <i class="fas fa-gift"></i><span>CDK管理</span>
            </a>
            <a href="orders.php" class="nav-link" data-tooltip="订单管理">
                <i class="fas fa-shopping-cart"></i><span>订单管理</span>
            </a>
            <a href="payments.php" class="nav-link" data-tooltip="支付记录">
                <i class="fas fa-credit-card"></i><span>支付记录</span>
            </a>
            <a href="settings.php" class="nav-link active" data-tooltip="系统设置">
                <i class="fas fa-cog"></i><span>系统设置</span>
            </a>
            <a href="logout.php" class="nav-link" data-tooltip="退出登录">
                <i class="fas fa-sign-out-alt"></i><span>退出登录</span>
            </a>
        </nav>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 页面标题 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="fas fa-cog me-2"></i>系统设置
            </h2>
            <div class="text-muted">
                <i class="fas fa-calendar me-2"></i><?php echo date('Y年m月d日 H:i:s'); ?>
            </div>
        </div>

                <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show">
                        <?php echo $message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- 系统信息卡片 -->
                <div class="row mb-4">
                    <div class="col-md-4">
                        <div class="info-card">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6>PHP版本</h6>
                                    <h4><?php echo $systemInfo['php_version']; ?></h4>
                                </div>
                                <i class="fas fa-code fa-2x opacity-50"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="info-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6>MySQL版本</h6>
                                    <h4><?php echo $systemInfo['mysql_version']; ?></h4>
                                </div>
                                <i class="fas fa-database fa-2x opacity-50"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="info-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6>服务器</h6>
                                    <h4><?php echo substr($systemInfo['server_software'], 0, 15); ?>...</h4>
                                </div>
                                <i class="fas fa-server fa-2x opacity-50"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 设置表单 -->
                <div class="settings-section">
                    <ul class="nav nav-tabs" id="settingsTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="system-tab" data-bs-toggle="tab" data-bs-target="#system" type="button" role="tab">
                                <i class="fas fa-globe"></i> 系统设置
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="payment-tab" data-bs-toggle="tab" data-bs-target="#payment" type="button" role="tab">
                                <i class="fas fa-credit-card"></i> 支付设置
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="security-tab" data-bs-toggle="tab" data-bs-target="#security" type="button" role="tab">
                                <i class="fas fa-shield-alt"></i> 安全设置
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="email-tab" data-bs-toggle="tab" data-bs-target="#email" type="button" role="tab">
                                <i class="fas fa-envelope"></i> 邮件设置
                            </button>
                        </li>
                    </ul>

                    <div class="tab-content" id="settingsTabsContent">
                        <!-- 系统设置 -->
                        <div class="tab-pane fade show active" id="system" role="tabpanel">
                            <div class="form-section">
                                <form method="POST">
                                    <input type="hidden" name="action" value="update_system">
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">网站名称</label>
                                                <input type="text" class="form-control" name="site_name" value="<?php echo htmlspecialchars($currentSettings['site_name']); ?>" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">网站URL</label>
                                                <input type="url" class="form-control" name="site_url" value="<?php echo htmlspecialchars($currentSettings['site_url']); ?>" required>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">管理员邮箱</label>
                                                <input type="email" class="form-control" name="admin_email" value="<?php echo htmlspecialchars($currentSettings['admin_email']); ?>" required>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="mb-3">
                                                <label class="form-label">货币单位</label>
                                                <select class="form-select" name="currency">
                                                    <option value="CNY" <?php echo $currentSettings['currency'] === 'CNY' ? 'selected' : ''; ?>>人民币 (CNY)</option>
                                                    <option value="USD" <?php echo $currentSettings['currency'] === 'USD' ? 'selected' : ''; ?>>美元 (USD)</option>
                                                    <option value="EUR" <?php echo $currentSettings['currency'] === 'EUR' ? 'selected' : ''; ?>>欧元 (EUR)</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="mb-3">
                                                <label class="form-label">时区</label>
                                                <select class="form-select" name="timezone">
                                                    <option value="Asia/Shanghai" <?php echo $currentSettings['timezone'] === 'Asia/Shanghai' ? 'selected' : ''; ?>>亚洲/上海</option>
                                                    <option value="America/New_York" <?php echo $currentSettings['timezone'] === 'America/New_York' ? 'selected' : ''; ?>>美国/纽约</option>
                                                    <option value="Europe/London" <?php echo $currentSettings['timezone'] === 'Europe/London' ? 'selected' : ''; ?>>欧洲/伦敦</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save"></i> 保存系统设置
                                    </button>
                                </form>
                            </div>
                        </div>

                        <!-- 支付设置 -->
                        <div class="tab-pane fade" id="payment" role="tabpanel">
                            <div class="form-section">
                                <form method="POST">
                                    <input type="hidden" name="action" value="update_payment">
                                    
                                    <h5 class="mb-3">易支付配置</h5>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">商户ID (PID)</label>
                                                <input type="text" class="form-control" name="easypay_pid" value="<?php echo htmlspecialchars($currentSettings['easypay_pid']); ?>" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">商户密钥 (Key)</label>
                                                <input type="password" class="form-control" name="easypay_key" value="<?php echo htmlspecialchars($currentSettings['easypay_key']); ?>" required>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">API地址</label>
                                        <input type="url" class="form-control" name="easypay_api_url" value="<?php echo htmlspecialchars($currentSettings['easypay_api_url']); ?>" required>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">回调地址</label>
                                                <input type="url" class="form-control" name="notify_url" value="<?php echo htmlspecialchars($currentSettings['easypay_notify_url']); ?>" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">返回地址</label>
                                                <input type="url" class="form-control" name="return_url" value="<?php echo htmlspecialchars($currentSettings['easypay_return_url']); ?>" required>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save"></i> 保存支付设置
                                    </button>
                                </form>
                            </div>
                        </div>

                        <!-- 安全设置 -->
                        <div class="tab-pane fade" id="security" role="tabpanel">
                            <!-- 密码修改表单 -->
                            <div class="form-section mb-4">
                                <h5 class="mb-3">
                                    <i class="fas fa-key me-2"></i>修改管理员密码
                                </h5>
                                <form method="POST">
                                    <input type="hidden" name="action" value="change_password">
                                    
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="mb-3">
                                                <label class="form-label">当前密码</label>
                                                <input type="password" class="form-control" name="current_password" required>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="mb-3">
                                                <label class="form-label">新密码</label>
                                                <input type="password" class="form-control" name="new_password" required minlength="6">
                                                <div class="form-text">密码长度至少6位</div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="mb-3">
                                                <label class="form-label">确认新密码</label>
                                                <input type="password" class="form-control" name="confirm_password" required minlength="6">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <button type="submit" class="btn btn-warning">
                                        <i class="fas fa-key me-2"></i> 修改密码
                                    </button>
                                </form>
                            </div>
                            
                            <!-- 系统安全设置 -->
                            <div class="form-section">
                                <h5 class="mb-3">
                                    <i class="fas fa-shield-alt me-2"></i>系统安全设置
                                </h5>
                                <form method="POST">
                                    <input type="hidden" name="action" value="update_security">
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">最大登录尝试次数</label>
                                                <input type="number" class="form-control" name="max_login_attempts" value="<?php echo htmlspecialchars($currentSettings['max_login_attempts']); ?>" min="1" max="10">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">会话超时时间 (分钟)</label>
                                                <input type="number" class="form-control" name="session_timeout" value="<?php echo htmlspecialchars($currentSettings['session_timeout']); ?>" min="5" max="1440">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" name="enable_captcha" id="enableCaptcha" <?php echo $currentSettings['enable_captcha'] === '1' ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="enableCaptcha">
                                                启用验证码
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" name="enable_2fa" id="enable2fa" <?php echo $currentSettings['enable_2fa'] === '1' ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="enable2fa">
                                                启用双因素认证
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save"></i> 保存安全设置
                                    </button>
                                </form>
                            </div>
                        </div>

                        <!-- 邮件设置 -->
                        <div class="tab-pane fade" id="email" role="tabpanel">
                            <div class="form-section">
                                <form method="POST">
                                    <input type="hidden" name="action" value="update_email">
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">SMTP服务器</label>
                                                <input type="text" class="form-control" name="smtp_host" value="<?php echo htmlspecialchars($currentSettings['smtp_host']); ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">SMTP端口</label>
                                                <input type="number" class="form-control" name="smtp_port" value="<?php echo htmlspecialchars($currentSettings['smtp_port']); ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">SMTP用户名</label>
                                                <input type="text" class="form-control" name="smtp_user" value="<?php echo htmlspecialchars($currentSettings['smtp_user']); ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">SMTP密码</label>
                                                <input type="password" class="form-control" name="smtp_pass" value="<?php echo htmlspecialchars($currentSettings['smtp_pass']); ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">发件人邮箱</label>
                                                <input type="email" class="form-control" name="from_email" value="<?php echo htmlspecialchars($currentSettings['from_email']); ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">发件人名称</label>
                                                <input type="text" class="form-control" name="from_name" value="<?php echo htmlspecialchars($currentSettings['from_name']); ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" name="enable_smtp" id="enableSmtp" <?php echo $currentSettings['enable_smtp'] === '1' ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="enableSmtp">
                                                启用SMTP邮件发送
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save"></i> 保存邮件设置
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="assets/admin.js"></script>
</body>
</html>
